import Sortable from 'sortablejs'
// import {
//   getCategoryList,
//   updateCategory,
//   deleteCategory,
//   updateCategorySort
// } from '@/api/category/index2'

import Req from '@/api/category'

export default {
  name: 'CategorySort',
  data() {
    return {
      loading: false,
      categoryList: [],
      productDialogVisible: false,
      productLoading: false,
      productList: [],
      currentCategory: {},
      sortable: null
    }
  },
  mounted() {
    this.getList()
    this.initSortable()
  },
  methods: {
    // 获取类别列表
    async getList() {
      this.loading = true
      try {
        const res = await Req.getCategoryList()
        this.categoryList = res.map(item => ({
          ...item,
          isEdit: false
        }))
      } catch (error) {
        console.error('获取类别列表失败：', error)
      } finally {
        this.loading = false
      }
    },

    // 初始化拖拽排序
    initSortable() {
      const el = document.querySelector('.el-table__body-wrapper tbody')
      this.sortable = Sortable.create(el, {
        handle: '.sort-handle',
        animation: 150,
        onEnd: async ({ oldIndex, newIndex }) => {
          if (oldIndex === newIndex) return

          const categoryList = [...this.categoryList]
          const currRow = categoryList.splice(oldIndex, 1)[0]
          categoryList.splice(newIndex, 0, currRow)

          // 更新排序
          try {
            const movingItem = categoryList[oldIndex]
            console.log(movingItem, oldIndex, newIndex)
            // 更新所有受影响项的排序
            if (oldIndex < newIndex) {
              // 向后移动：中间项的排序号减1
              for (let i = oldIndex; i <= newIndex; i++) {
                categoryList[i].sortIndex = i + 1
              }
            } else {
              // 向前移动：中间项的排序号加1
              for (let i = newIndex; i < oldIndex; i++) {
                categoryList[i].sortIndex = i + 1
              }
              this.categoryList.find(e => e.categoryName === movingItem.categoryName).sortIndex = oldIndex + 1
            }

            await Req.updateCategory({
              sortList: categoryList
            })


            // await Req.updateCategory({
            //   id: currRow.id,
            //   oldIndex: oldIndex + 1,
            //   newIndex: newIndex + 1
            // })
            // await updateCategorySort({
            //   id: currRow.id,
            //   oldIndex,
            //   newIndex
            // })
            this.categoryList = categoryList
            this.$message.success('排序更新成功')
          } catch (error) {
            this.$message.error('排序更新失败')
            // 还原排序
            this.getList()
          }
        }
      })
    },

    // 新增类别
    handleAdd() {
      this.categoryList.unshift({
        id: Date.now(),
        name: '',
        code: '',
        status: 1,
        isEdit: true
      })
    },

    // 编辑类别
    handleEdit(row) {
      row.isEdit = true
      this.$nextTick(() => {
        const input = document.querySelector('.el-table__row:first-child .el-input__inner')
        input && input.focus()
      })
    },

    // 保存类别
    async handleSave(row) {
      if (!row.name.trim()) {
        this.$message.warning('类别名称不能为空')
        return
      }

      try {
        await updateCategory(row)
        row.isEdit = false
        this.$message.success('保存成功')
      } catch (error) {
        this.$message.error('保存失败')
      }
    },

    // 更改状态
    async handleStatusChange(row) {
      try {
        await updateCategory(row)
        this.$message.success('状态更新成功')
      } catch (error) {
        // 还原状态
        row.status = row.status === 1 ? 0 : 1
        this.$message.error('状态更新失败')
      }
    },

    // 查看商品
    async handleViewProducts(row) {
      this.currentCategory = row
      this.productDialogVisible = true
      this.productLoading = true

      try {
        const res = await getProductsByCategory(row.id)
        this.productList = res.data
      } catch (error) {
        console.error('获取商品列表失败：', error)
      } finally {
        this.productLoading = false
      }
    },

    // 删除类别
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该类别?', '提示', {
          type: 'warning'
        })

        await deleteCategory(row.id)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    }
  }
}